const { Sequelize,Model } = require('sequelize')
const validator = require('validator')
const sequelize = require('../core/db')
const { generateToken } = require('../core/utils')
const Code = require('./code')

class User extends Model{
    static async isRegister(phone) {
        const user = await User.findOne({
            where:{phone}
        })
        return user ? true : false
    }

    static async login(username, password,ctx) {
        let user
        if (validator.isEmail(username)) {
            user = await User.findOne({where:{email: username,password}})
        } else {
            user = await User.findOne({where:{phone: username,password}})
        }
        if (user) {
            let token = generateToken(user.uid,user)
            ctx.body = {token}
        } else {
            throw new global.errs.NotFound('登录信息错误')
        }
    }

    static async codeLogin(phone,code,ctx) {
        const codeResult = await Code.findOne({ where: { phone,code } })
        if (!codeResult) {
            throw new global.errs.NotFound('验证码错误')
        } else {
            const user = await User.findOne({where:{phone}})
            let token = generateToken(user.uid,user)
            ctx.body = {token}
        }
    }

    static async register( phone, password, code,ctx) {
        const isRegister = await User.isRegister(phone)
        if (isRegister) {
            throw new global.errs.Success('该手机号已被注册')
        }
        
        const codeResult = await Code.findOne({ where: { phone,code } })
        if (!codeResult) {
            throw new global.errs.Success('验证码错误')
        } else {
            const user = await User.create({
                phone,
                password
            })
            throw new global.errs.Success('注册成功')
        }
    }

    static async getCode(phone) {
        const codeRow = await Code.findOne({ where: { phone } })
        const code = Math.floor(Math.random() * 1000000)
        await getCode(phone,code)
        if (!codeRow) {
            await Code.create({phone,code})
        } else {
            await Code.update({code},{where:{phone}})
        }
        throw new global.errs.Success('获取验证码成功')
    }
 }

User.init({
    uid: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement:true
    },
    phone:Sequelize.BIGINT(11) ,
    email:Sequelize.STRING,
    password:Sequelize.STRING
}, {
    sequelize,
    tableName: 'user'
})

module.exports = User